package com.itheima.travel.service.impl;

import com.itheima.travel.constant.RedisConstant;
import com.itheima.travel.mapper.CategoryMapper;
import com.itheima.travel.pojo.Category;
import com.itheima.travel.pojo.CategoryExample;
import com.itheima.travel.req.CategoryVo;
import com.itheima.travel.service.CategoryService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 查询所有分类
     *
     * @return
     */
    @Override
    public List<CategoryVo> findAllCategory() {
        //查询缓存
        String key = RedisConstant.CATEGORYSERVICE_FINDALLCATEGORY;
        RBucket<List<CategoryVo>> bucket = redissonClient.getBucket(key);
        List<CategoryVo> categoryVoList = bucket.get();
        if (!EmptyUtil.isNullOrEmpty(categoryVoList)) {
            return categoryVoList;
        }
        //如果没有则查询数据库
        CategoryExample example = new CategoryExample();
        List<Category> categoryList = categoryMapper.selectByExample(example);
        //更新缓存
        if (!EmptyUtil.isNullOrEmpty(categoryList)) {
            bucket.set(BeanConv.toBeanList(categoryList, CategoryVo.class), 1800, TimeUnit.SECONDS);

        }
        return BeanConv.toBeanList(categoryList, CategoryVo.class);
    }
}
